package com.zjshell.pricing.fileUpload;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.zjshell.pricing.common.annotation.ControllerEndpoint;
import com.zjshell.pricing.common.controller.BaseController;
import com.zjshell.pricing.common.entity.FebsResponse;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("imageUpload")
public class UploadImgController extends BaseController {

    @Value("shell")
    private String prefix;

    @PostMapping("doUploadImg")
    @ControllerEndpoint(exceptionMessage = "上传图片失败")
    public FebsResponse uploadImg(@RequestParam("img") MultipartFile img, HttpServletRequest request, HttpServletResponse response) {
        String contentType = img.getContentType();    // 获取文件的类型
        System.out.println("文件类型为：" + contentType);
        String originalFilename = img.getOriginalFilename();     // 获取文件的原始名称
        // 判断文件是否为空
        if (!img.isEmpty()) {
            File targetImg = new File("/Users/vargent/Desktop/images");
            // 判断文件夹是否存在
            if (!targetImg.exists()) {
                targetImg.mkdirs();    //级联创建文件夹
            }
            try {
                // 开始保存图片
                FileOutputStream outputStream = new FileOutputStream("/Users/vargent/Desktop/images/" + originalFilename);
                outputStream.write(img.getBytes());
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return new FebsResponse().success().data("/Users/vargent/Desktop/images/"+originalFilename);
    }


    private String getFileName(String fileName) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyMM");
        String filename = formatter.format(new Date());
        filename = filename + "/" + UUID.randomUUID().toString();
        String ext = fileName;
        ext = ext.substring(ext.lastIndexOf(".") + 1);
        filename = this.prefix + filename + "." + ext;
        return filename;
    }
}
